package com.bupt.ilink.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.entity.folder.Folder;
import com.bupt.ilink.entity.store.Flow;
import com.bupt.ilink.mapper.FlowMapper;
import com.bupt.ilink.mapper.FolderMapper;
import com.bupt.ilink.request.Application.CreateFolderRequest;
import com.bupt.ilink.request.Application.PersonalFlowQueryByFolderConditionRequest;
import com.bupt.ilink.response.Applicaition.PersonalFlowQueryByFolderResponse;
import com.bupt.ilink.service.PersonalFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class PersonalFlowServiceImpl implements PersonalFlowService {
    @Autowired
    private FolderMapper folderMapper;
    @Autowired
    private FlowMapper flowMapper;


    @Override
    public PersonalFlowQueryByFolderResponse getAppsInFolder(PersonalFlowQueryByFolderConditionRequest params) {
        // 1. 根据folderId查询Folder表
        Folder folder = folderMapper.selectById(params.getFolderId());
        if (folder == null) {
            throw new RuntimeException("Folder not found for ID: " + params.getFolderId());
        }

        // 2. 初始化响应对象
        PersonalFlowQueryByFolderResponse response = new PersonalFlowQueryByFolderResponse();
        response.setFolderId(folder.getFolderId());
        response.setName(folder.getName());
        response.setDescription(folder.getDescription());
        response.setParentId(folder.getParentId());

        // 3. 设置分页参数
        Page<Flow> page = new Page<>(params.getPageNumber(), params.getPageSize());

        // 4. 根据folderId查询flow表并分页
        QueryWrapper<Flow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("folder_id", params.getFolderId());

        Page<Flow> flowPage = flowMapper.selectPage(page, queryWrapper);

        // 5. 将分页结果的flow列表设置到响应对象中
        response.setFlows(flowPage.getRecords());

        return response;
    }
    @Override
    public Folder createFolder(CreateFolderRequest createFolderRequest) {
        // 从SecurityContextHolder中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        String userId = user.getUserId();

        Folder folder = new Folder();
        // 设置folder对象的userId和随机生成的folderId
        folder.setFolderId(UUID.randomUUID().toString());
        folder.setUserId(userId);

        // 获取并设置name和description
        String originalName = createFolderRequest.getName();

        System.out.println(createFolderRequest.getName());
        if (originalName == null || originalName.isEmpty()) {
            originalName = Folder.DEFAULT_FOLDER_NAME; // 如果name为空，使用默认名称
        }
        folder.setDescription(Folder.DEFAULT_FOLDER_DESCRIPTION);

        String folderName = originalName;
        int suffix = 0;

        // 检查当前用户下是否存在同名文件夹
        while (folderExistsForUser(userId, folderName)) {
            suffix++;
            folderName = originalName + " (" + suffix + ")";
        }

        // 设置最终的唯一名称
        folder.setName(folderName);

        // 调用Mapper插入数据到数据库
        folderMapper.insert(folder);

        // 返回创建的Folder对象
        return folder;
    }

    /**
     * 检查当前用户是否已存在同名文件夹
     */
    private boolean folderExistsForUser(String userId, String folderName) {
        // 在数据库中查询是否存在同名文件夹
        return folderMapper.selectCount(new QueryWrapper<Folder>()
                .eq("user_id", userId)
                .eq("name", folderName)) > 0;
    }



    @Override
    public Folder changeFolderInfo(String folderId, CreateFolderRequest createFolderRequest){
        // 查找数据库中是否存在指定的 folderId
        Folder folder = folderMapper.selectById(folderId);

        if (folder == null) {
            // 处理未找到文件夹的情况（可以抛出异常或者返回一个错误提示）
            throw new RuntimeException("Folder not found with id: " + folderId);
        }

        // 更新文件夹的名称和描述（你可以根据请求参数来更新其他属性）
        if (createFolderRequest.getName() != null) {
            folder.setName(createFolderRequest.getName());
        }

        if (createFolderRequest.getDescription() != null) {
            folder.setDescription(createFolderRequest.getDescription());
        }

        // 将更新后的文件夹保存到数据库
        folderMapper.updateById(folder);

        // 返回更新后的文件夹对象
        return folder;
    }

    @Override
    public Boolean deleteFolder(String folderId){
        // 查找数据库中是否存在指定的 folderId
        Folder folder = folderMapper.selectById(folderId);

        if (folder == null) {
            // 处理未找到文件夹的情况（可以抛出异常或者返回一个错误提示）
            throw new RuntimeException("Folder not found with id: " + folderId);
        }

        // 从数据库中删除该文件夹
        int deleted = folderMapper.deleteById(folderId);

        // 返回删除操作是否成功
        return deleted > 0;
    }

    @Override
    public String deleteFlows(List<String> flowIds) {
        int totalCount = flowIds.size();
        int deletedCount = 0;
        int failedCount = 0;

        // 遍历每个 flowId，尝试删除
        for (String flowId : flowIds) {
            try {
                // 单个删除，如果返回值 > 0 则删除成功
                int result = flowMapper.deleteById(flowId);
                if (result > 0) {
                    deletedCount++;
                } else {
                    failedCount++;
                }
            } catch (Exception e) {
                // 捕获异常，并计入失败的删除操作
                failedCount++;
            }
        }

        // 返回处理结果的字符串
        return String.format("共收到%d个，%d个删除成功，%d个删除失败", totalCount, deletedCount, failedCount);
    }

}
